#include <iostream>
#include <memory>
#include "http.hpp"
#include "HttpProtocol.hpp"

std::string SuffixToType(const std::string &suffix)
{
    if (suffix == ".html")
        return "text/html";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else if (suffix == ".png")
        return "image/png";
    else
        return "text/html";
    return "text/html";
}

std::string CodeToDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 302:
        return "Found";
    case 307:
        return "Temporary Redirect";
    case 404:
        return "Not Found";
    default:
        return "Unknown";
    }
    return "";
}

// 服务器对业务的处理逻辑
std::string HandlerHttpRequest(std::string &request)
{
    HttpRequest httpreq;
    // 反序列化
    httpreq.Deserialize(request);
    httpreq.Parse();
    httpreq.DebugHttp();
    std::string content = httpreq.GetFileContent();
    int code = 200;

    if (content.empty())
    {
        code = 404;
        content = httpreq.Get_404();
    }
    code = 307; // 307重定向到新的网站

    // 服务器得到客户端的请求之后做出响应
    HttpResponse httpresp;
    httpresp.SetStatusCode(code);
    httpresp.SetStatusCodeDesc(CodeToDesc(code));
    httpresp.MakeStatusLine();

    std::string content_len_str = "Content-Length: " + std::to_string(content.size()) + "\r\n";
    httpresp.AddResqHeader(content_len_str);
    std::string content_type_str = "Content-Type: " + SuffixToType(httpreq.GetSuffix()) + "\r\n";
    httpresp.AddResqHeader(content_type_str);
    std::string location = "Location: /404.html\r\n";
    httpresp.AddResqHeader(location);
    httpresp.AddContent(content);

    return httpresp.Serialize();
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " serverport" << std::endl;
        return 1;
    }

    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<HttpServer> tvr(new HttpServer(localport, HandlerHttpRequest));
    tvr->Loop();

    return 0;
}